package com.quick.threadtest;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest {
    final ReentrantLock lock = new ReentrantLock();//锁对象
    final Condition notFull  = lock.newCondition();//写线程条件
    final Condition notEmpty = lock.newCondition();//读线程条件
    final Object[] items = new Object[10];//缓存队列
    private int count = 0;
    private int putptr=0;
    private int takeptr=0;
//    ArrayBlockingQueue
    public void put(Object x) throws InterruptedException {
        lock.lock();
        System.out.println("put");
        try {
            while (count == items.length){
                System.out.println("阻塞了写线程");
                //如果队列满了
                notFull.await();//阻塞写线程
            }
            items[putptr] = x;//赋值
            if (++putptr == items.length) putptr = 0;//如果写索引写到队列的最后一个位置了，那么置为0
            ++count;//个数++
            notEmpty.signal();//唤醒读线程
        } finally {
            lock.unlock();
        }
    }

    public Object take() throws InterruptedException {
        System.out.println("take");
        lock.lock();
        try {
            while (count == 0){
                System.out.println("阻塞了读线程");
                //如果队列为空
                notEmpty.await();//阻塞读线程
            }

            Object x = items[takeptr];//取值
            if (++takeptr == items.length) takeptr = 0;//如果读索引读到队列的最后一个位置了，那么置为0
            --count;//个数--
            notFull.signal();//唤醒写线程
            return x;
        } finally {
            lock.unlock();
        }
    }

}
